package sas

import (
	"fmt"

	"gitee.com/micro-plat/sas/sas/services/auth"
	"gitee.com/micro-plat/sas/sas/services/cipher"
	"github.com/micro-plat/hydra"
	"github.com/micro-plat/hydra/services"
)

var cacheServices []string = make([]string, 0, 5)

//Bind 将SSO服务注册到应用服务器
func Bind(registry services.IMicroRegistry, opts ...ConfOption) error {

	Unbind()

	for i := range opts {
		opts[i]()
	}

	registryNow(registry, servicePrefix, "/multi/:type1/:type2/auth", auth.NewMultiHandler)
	registryNow(registry, servicePrefix, "/dynamic/:type1/:type2/auth", auth.NewDynamicHandler)

	/*认证服务接口*/
	registryNow(registry, servicePrefix, "/single/:type1/auth", auth.NewSingleHandler)
	/*加解密模式接口*/
	registryNow(registry, servicePrefix, "/cipher/:type/generate", cipher.NewGenerateHandler)
	registryNow(registry, servicePrefix, "/cipher/:type/get", cipher.NewGetHandler)
	registryNow(registry, servicePrefix, "/cipher/:type/reset", cipher.NewResetHandler)
	registryNow(registry, servicePrefix, "/cipher/:type/enable", cipher.NewEnableHandler)
	registryNow(registry, servicePrefix, "/cipher/:type/disable", cipher.NewDisableHandler)
	registryNow(registry, servicePrefix, "/cipher/:type/set", cipher.NewSetHandler)

	return nil
}

//Unbind 解除服务绑定
func Unbind() {
	for _, s := range cacheServices {
		hydra.S.Remove(s)
	}
	cacheServices = make([]string, 0, 5)

}

//registryNow 注册并缓存服务
func registryNow(registry services.IMicroRegistry, servicePrefix string, service string, handler interface{}) {
	name := fmt.Sprintf("%s%s", servicePrefix, service)
	registry(name, handler)
	cacheServices = append(cacheServices, name)
}
